package com.uzai.console.queue;

import cn.hutool.core.date.DateUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.concurrent.DelayQueue;

/**
 * @author mingyang.chen create in 2024/3/25 19:02
 */
@Slf4j
public class ConsoleDelayProducer {

    public static final ConsoleDelayProducer instance = new ConsoleDelayProducer();

    @Getter
    private static final DelayQueue<ConsoleDelayTask> delayQueue = new DelayQueue<>();

    private ConsoleDelayProducer() {
    }

    public synchronized void addDelayTask(ConsoleDelayTask delayTask) {
        if (Objects.nonNull(delayTask)) {
            if (delayQueue.contains(delayTask)) {
                log.info("添加新的延时任务失败, 队列中已存在相同的任务");
                return;
            }
            Long delay = delayTask.getDelay();
            log.info("添加新的延时任务, 执行时间: {}, key: {}", DateUtil.date(delay), delayTask.getName() + "-" + delayTask.getTaskId());
            delayQueue.offer(delayTask);
        }
    }

    public synchronized void removeTask(ConsoleDelayTask delayTask) {
        if (Objects.nonNull(delayTask)) {
            delayQueue.remove(delayTask);
        }
    }

    public synchronized void removeTask(Long taskId) {
        delayQueue.removeIf(next -> next.getTaskId().equals(taskId));
    }
}
